<template>
  <div class="bag">
    <div class="bag-top">
      <van-nav-bar
        title="购物袋"
        left-text="返回"
        left-arrow
        :right-text="isText ? '完成' : '编辑'"
        @click-right="onClickRight"
        @click-left="onClickLeft"
      />
    </div>
    <div class="bag-bg"></div>
    <div class="product-box" v-if="shopBagData.length > 0">
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoadData"
      >
        <div class="info-box" v-for="(item, i) in shopBagData" :key="item.sid">
          <van-swipe-cell :disabled="isText">
            <div class="dot">
              <van-checkbox
                v-model="item.isChecked"
                checked-color="#7F2F21"
                @click="singleCheck"
              ></van-checkbox>
            </div>
            <van-card
              :price="item.price"
              :desc="item.rule"
              :title="item.name"
              class="goods-card"
              :thumb="item.small_img"
            >
              <template #footer>
                <div class="num">
                  <van-stepper
                    v-model="item.count"
                    theme="round"
                    button-size="22"
                    disable-input
                    @change="updateProductCount(item.sid, item.count)"
                  />
                </div>
              </template>
            </van-card>
            <template #right>
              <van-button
                square
                text="删除"
                type="danger"
                class="delete-button"
                @click="dele([item.sid], i)"
              />
            </template>
          </van-swipe-cell>
        </div>
      </van-list>
    </div>

    <!-- 没有数据时提醒 -->
    <div v-else class="empty">
      <van-empty
        class="custom-image"
        image="https://img.yzcdn.cn/vant/custom-empty-image.png"
        description="1 + 1 > 2 为心爱的他/她点一点"
      >
        <van-button round type="danger" class="bottom-button" @click="gohome"
          >点一点</van-button
        >
      </van-empty>
    </div>
    <van-submit-bar
      v-show="!isText"
      :price="total"
      button-text="提交订单"
      button-color="#7F2F21"
      @submit="subOrder"
    >
      <van-checkbox v-model="checkedAll" @click="allChoice">全选</van-checkbox>
    </van-submit-bar>
    <van-submit-bar
      v-show="isText"
      button-text="删除选择"
      button-color="#7F2F21"
      @submit="deleChoice"
    >
      <van-checkbox v-model="checkedAll" @click="allChoice">全选</van-checkbox>
    </van-submit-bar>
  </div>
</template>

<script>
import "../assets/less/bag.less";
import { mapMutations, mapState } from "vuex";
// import Product from "../components/Product.vue";
export default {
  name: "Bag",
  components: {
    // Product,
  },
  data() {
    return {
      // 点击编辑
      isText: false,

      // 购物袋所有数据
      shopBagAllData: [],

      // 购物袋数据
      shopBagData: [],

      // 开始截取位置
      start: 0,

      // 每次截取的5条数据
      number: 8,

      // 是否加载,第一次不触发
      loading: true,

      // 是否加载完成
      finished: false,

      // 全选或者取消全选
      checkedAll: false,

      // 总金额
      total: 0,
    };
  },
  computed: {
    ...mapState(["shopBag"]),
  },

  created() {
    // 获取所有购物袋数据
    this.getBagData();
  },

  methods: {
    ...mapMutations(["changeShopBag"]),
    // 点击编辑
    onClickRight() {
      this.isText = !this.isText;
    },

    //返回上一级
    onClickLeft() {
      this.$router.go(-1);
    },

    // 获取所有购物袋的数据
    getBagData() {
      let tokenString = this.$cookies.get("tokenString");

      //当用户未登录的时候跳转到登录页面
      if (!tokenString) {
        return this.$router.push({ name: "Login" });
      }

      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        duration: 0,
      });

      this.axios({
        method: "get",
        url: this.baseUrl + "/findAllShopcart",
        params: {
          appkey: this.appkey,
          tokenString: tokenString,
        },
      })
        .then((result) => {
          console.log(result);
          this.$toast.clear();
          if (result.data.code === 700) {
            this.$toast({
              message: result.data.msg,
              forbidClick: true,
              duration: 3000,
            });
            return this.$router.push({ name: "Login" });
          }
          if (result.data.code === 5000) {
            result.data.result.forEach((v) => {
              v.isChecked = false;
            });

            this.shopBagAllData = result.data.result;

            this.shopBagData = this.shopBagAllData.slice(
              this.start,
              this.start + this.number
            );

            this.start += this.number;

            if (this.shopBagAllData.length < this.number) {
              this.finished = true;
              return;
            }

            this.loading = false;
          } else {
            this.$toast({
              message: result.data.msg,
              forbidClick: true,
              duration: 3000,
            });
          }
        })
        .catch((err) => {
          this.$toast.clear();
          console.log(err);
        });
    },

    // 更新产品数据加减
    updateProductCount(sid, count) {
      let tokenString = this.$cookies.get("tokenString");

      //当用户未登录的时候跳转到登录页面
      if (!tokenString) {
        return this.$router.push({ name: "Login" });
      }

      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        duration: 0,
      });

      this.axios({
        method: "post",
        url: this.baseUrl + "/modifyShopcartCount",
        data: {
          appkey: this.appkey,
          tokenString: tokenString,
          sid,
          count,
        },
      })
        .then((result) => {
          console.log(result);
          this.$toast.clear();
          if (result.data.code === 700) {
            this.$toast({
              message: result.data.msg,
              forbidClick: true,
              duration: 3000,
            });
            return this.$router.push({ name: "Login" });
          }
          if (result.data.code === 6000) {
            this.sum();
          } else {
            this.$toast({
              message: result.data.msg,
              forbidClick: true,
              duration: 3000,
            });
          }
        })
        .catch((err) => {
          this.$toast.clear();
          console.log(err);
        });
    },

    // 全选
    allChoice() {
      this.shopBagData.forEach((v) => {
        v.isChecked = this.checkedAll;
      });
      // 计算金额
      this.sum();
    },

    // 单选
    singleCheck() {
      // 计算金额
      this.sum();
      if (this.shopBagData.length === 0) {
        this.checkedAll = false;
        return;
      }
      for (let i = 0; i < this.shopBagData.length; i++) {
        if (!this.shopBagData[i].isChecked) {
          this.checkedAll = false;
          return;
        }
      }
      this.checkedAll = true;
    },

    // 删除
    dele(sids, i) {
      // this.shopBagData.splice(i, 1);
      // console.log(this.shopBagData.length)
      // return;
      // console.log(sids, i);
      let tokenString = this.$cookies.get("tokenString");

      //当用户未登录的时候跳转到登录页面
      if (!tokenString) {
        return this.$router.push({ name: "Login" });
      }

      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        duration: 0,
      });

      this.axios({
        method: "post",
        url: this.baseUrl + "/deleteShopcart",
        data: {
          appkey: this.appkey,
          tokenString: tokenString,
          sids: JSON.stringify(sids),
        },
      })
        .then((result) => {
          // console.log(result);
          this.$toast.clear();
          if (result.data.code === 700) {
            this.$toast({
              message: result.data.msg,
              forbidClick: true,
              duration: 3000,
            });
            return this.$router.push({ name: "Login" });
          }
          if (result.data.code === 7000) {
            // 单个删除
            if (i !== undefined) {
              this.shopBagData.splice(i, 1);
              this.changeShopBag(this.shopBag - 1);
              this.singleCheck();
              console.log(this.shopBagData);
            } else {
              // 多个删除
              for (let k = 0; k < this.shopBagData.length; k++) {
                if (this.shopBagData[k].isChecked) {
                  this.shopBagData.splice(k, 1);
                  k--;
                }
              }
              this.changeShopBag(this.shopBag - sids.length);
              this.sum();
              if (this.shopBagData.length == 0) {
                this.checkedAll = false;
              }
            }

            if (this.shopBagData.length < 5 && !this.finished) {
              this.onLoadData();
            }
          } else {
            this.$toast({
              message: result.data.msg,
              forbidClick: true,
              duration: 3000,
            });
          }
        })
        .catch((err) => {
          this.$toast.clear();
          console.log(err);
        });
    },

    // 删除选择的咖啡
    deleChoice() {
      let sids = [];
      this.shopBagData.forEach((v) => {
        if (v.isChecked) {
          sids.push(v.sid);
        }
      });

      if (sids.length === 0) {
        this.$toast({
          message: "请选择删除的商品",
          forbidClick: true,
          duration: 2000,
        });
        return;
      }
      this.dele(sids);
    },

    // 计算金额
    sum() {
      let total = 0;
      this.shopBagData.forEach((v) => {
        if (v.isChecked) {
          total += v.count * v.price;
        }
      });
      this.total = total * 100;
    },

    // 加载数据
    onLoadData() {
      console.log("加载数据中。。。");
      // console.log(this.loading);

      setTimeout(() => {
        let data = this.shopBagAllData.slice(
          this.start,
          this.start + this.number
        );
        this.start += this.number;

        this.shopBagData.push(...data);

        if (data.length < this.number) {
          this.finished = true;
          return;
        }

        this.loading = false;
      }, 1000);
    },

    // 提交订单
    subOrder() {
      let sids = []; //选中
      this.shopBagData.forEach((v) => {
        if (v.isChecked) {
          sids.push(v.sid);
        }
      });

      if (sids.length === 0) {
        this.$toast({
          message: "请选择购买的商品",
          forbidClick: true,
          duration: 2000,
        });
        return;
      }

      this.$router.push({
        name: "Order",query: { sids: sids.join("-") },});
    },

    // 跳转home
    gohome() {
      this.$router.push({ path: "/" });
    },
  },
};
</script>
